package com.nsapi.niceschoolapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nsapi.niceschoolapi.common.base.PageData;
import com.nsapi.niceschoolapi.common.util.ResponseEntity;
import com.nsapi.niceschoolapi.entity.Menu;
import com.nsapi.niceschoolapi.entity.Role;
import com.nsapi.niceschoolapi.entity.User;
import com.nsapi.niceschoolapi.service.MenuService;
import com.nsapi.niceschoolapi.service.RoleService;
import com.nsapi.niceschoolapi.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("admin/system/role")
public class RoleController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private MenuService menuService;

    // 跳转角色列表页
    @RequestMapping("list")
    public String toListVew() {
        return "admin/role/list";
    }

    // 按角色名查询
    @RequiresPermissions("sys:role:list")
    @PostMapping("list")
    @ResponseBody
    public Object list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                       String roleName) {
        PageData<Role> rolePageData = new PageData<>();
        QueryWrapper<Role> roleWrapper = new QueryWrapper<>();
        roleWrapper.eq("del_flag",false);
        if(StringUtils.isNotBlank(roleName)) {
            roleWrapper.like("name", roleName);
        }
        IPage<Role> rolePage = roleService.page(new Page<>(page,limit),roleWrapper);
        rolePageData.setCount(rolePage.getTotal());
        rolePageData.setData(setUserToRole(rolePage.getRecords()));
        return rolePageData;
    }

    private List<Role> setUserToRole(List<Role> roles){
        roles.forEach(r -> {
            if(StringUtils.isNotBlank(r.getCreateId())){
                User u = userService.findUserById(r.getCreateId());
                if(StringUtils.isBlank(u.getNickName())){
                    u.setNickName(u.getLoginName());
                }
                r.setCreateUser(u);
            }
            if(StringUtils.isNotBlank(r.getUpdateId())){
                User u  = userService.findUserById(r.getUpdateId());
                if(StringUtils.isBlank(u.getNickName())){
                    u.setNickName(u.getLoginName());
                }
                r.setUpdateUser(u);
            }
        });
        return roles;
    }

    // 跳转添加页
    @RequestMapping("add")
    public String toAddView(ModelMap modelMap) {
        List<Menu> menuList = menuService.selectAllMenuList(null);
        modelMap.put("menuList",menuList);
        return "admin/role/add";
    }

    // 添加角色
    @RequiresPermissions("sys:role:add")
    @PostMapping("add")
    @ResponseBody
    public Object add(@RequestBody Role role) {
        if(roleService.getRoleNameCount(role.getName())>0){
            return ResponseEntity.failure("角色名称已存在");
        }
        roleService.saveRole(role);
        return ResponseEntity.success("操作成功");
    }

    // 跳转修改页
    @RequestMapping("edit")
    public String toEditView(String id,ModelMap modelMap){
        Role role = roleService.getRoleById(id);
        String menuIds = null;
        if(role != null) {
            menuIds  = role.getMenuSet().stream().map(menu -> menu.getId()).collect(Collectors.joining(","));
        }
        Map<String,Object> map = new HashMap();
        map.put("parentId",null);
        map.put("isShow",Boolean.FALSE);
        List<Menu> menuList = menuService.selectAllMenus(map);
        modelMap.put("role",role);
        modelMap.put("menuList",menuList);
        modelMap.put("menuIds",menuIds);
        return "admin/role/edit";
    }

    //修改角色
    @RequiresPermissions("sys:role:edit")
    @PostMapping("edit")
    @ResponseBody
    public Object edit(@RequestBody Role role) {
        if(roleService.getRoleNameCount(role.getName())>0){
            return ResponseEntity.failure("角色名称已存在");
        }
        roleService.updateRole(role);
        return ResponseEntity.success("操作成功");
    }


    // 删除角色
    @RequiresPermissions("sys:role:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Object del(String id) {
        int result =  roleService.deleteRole(id);
        return ResponseEntity.success("操作成功");
    }

    // 批量删除
    @RequiresPermissions("sys:role:delete")
    @RequestMapping("deleteSome")
    @ResponseBody
    public Object deleteSome(@RequestBody List<Role> roles) {
        if(roles == null || roles.size()==0){
            return ResponseEntity.failure("请选择需要删除的角色");
        }
        for (Role r : roles){
            roleService.deleteRole(r.getId());
        }
        return ResponseEntity.success("操作成功");
    }


}
